<?php
declare (strict_types = 1);

namespace App\Models;


/**
 * 管理员表
 */
class SystemConfigModel extends BaseModel
{
    protected $table = 'system_config';
    protected $fillable = ['name','value','type'];
    const CREATED_AT = null;

    /**
     * 获取配置
     * @param string $type
     */
    public static function getConfig($type = 'website')
    {
        return self::where("type", $type)->pluck("value", "name");
    }

    /**
     * 保存config数据
     * @param  [type] $type 类型
     * @param  [type] $param 一维数组
     * @return [type]       [description]
     */
    public static function saveConfig($type, $param)
    {
        try {
            self::startTrans();
            if(!is_array($param)) {
                return self::result('',500,'相关参数不合法');
            }
            if(empty($type)) {
                return self::result('',500,'请填写类型相关值');
            }
            $list = self::getConfig($type);

            if(!$list->isEmpty()){
                //剔除无用列
                $diff_arr = array_diff_key($list->toArray(),$param);
                if($diff_arr) {
                    foreach ($diff_arr as $k => $v) {
                        self::where(['name'=>$k, 'type' => $type])->delete();
                    }
                    $list = self::getConfig($type);
                }
                foreach ($param as $k => $v){
                    $arr = ['name' => $k, 'value' => $v, 'type' => $type];
                    if(!isset($list[$k])){
                        $res = self::create($arr);
                    }else{
                        $res = self::where(['name' => $k, 'type' => $type])->update($arr);
                    }
                }
            }else{
                foreach ($param as $k => $v){
                    $arr[] = ['name' => $k, 'value' => $v, 'type' => $type];
                }
                $res = self::insert($arr);
            }
            if(!$res){
                self::rollback();
                return self::result('',500,'操作失败');
            }
            self::commit();
            return self::result('',200,'操作成功');
        } catch (\Exception $e) {
            self::rollback();
            return self::result('',500,$e->getMessage());
        }
    }
}
